const api = require("../../../api/sop");
import { log, err, toast } from "../../../utils/wxapi";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 手机验证码
    inputPhone: "",
    inputAuth: "",
    // 接口返回的验证码
    yesInfoAuth: "666666",
    user: {},
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getuser();
  },
  async getuser() {
    try {
      const res = await api.getUser();
      if (res.respCode === 200) {
        const user = JSON.parse(res.source);
        this.setData({ user });
      }
    } catch (error) {
      err(error);
    }
  },
  async avatar(e) {
    wx.showLoading({
      title: "上传中",
    });
    try {
      const { avatarUrl } = e.detail;
      const timestamp = new Date().valueOf();
      const res = await wx.cloud.uploadFile({
        cloudPath: "head_url/" + timestamp + ".png",
        filePath: avatarUrl,
      });
      const data = JSON.stringify({
        avatarUrl: res.fileID,
        userId: this.data.user.userId,
      });
      const ress = await api.putuser(data);
      if (ress.respCode === 200) {
        toast("修改成功");
        this.getuser();
      } else {
        toast("修改失败");
      }
    } catch (error) {
      err(error);
      toast("上传失败");
    }
  },
  async putname() {
    try {
      const res = await wx.showModal({
        title: "修改昵称",
        editable: true,
      });
      if (res.confirm) {
        const newUsername = res.content.trim(); // 获取用户输入的新昵称
        if (newUsername === "") {
          toast("昵称不能为空");
          return;
        }
        const data = JSON.stringify({
          name: newUsername,
          userId: this.data.user.userId,
        });
        const ress = await api.putuser(data);
        if (ress.respCode === 200) {
          toast("修改成功");
          this.getuser();
        } else {
          toast("修改失败");
        }
      }
    } catch (error) {
      err(error);
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},
});
